package com.udp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**UDP 通信的实现  传递自定义对象类型
 * 创建客服端*/
public class ObjectTypeClient {
    public static void main(String[] args) {
        ByteArrayOutputStream bos = null;//字节籹组输出流
        DatagramSocket datagramSocket = null;//数据发送
        ObjectOutputStream oos = null;//对象输出流
        try{
            //创建传输对象
            Person p = new Person();
            p.setName("Jack");
            p.setAge(32);
            /*先用ObjectOutputStream这个流对象，把要传递的对象输出到
            ByteArrayOutputStream ,再通过这个对象转换为字节数组*/
            //创建流对象
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(p);

            byte[] arr = bos.toByteArray();
            //封装
            DatagramPacket dp = new DatagramPacket(arr,arr.length,new InetSocketAddress("127.0.0.1",9999));
            //实现DatagramSocket 对象
            datagramSocket = new DatagramSocket(8888);
            datagramSocket.send(dp);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(datagramSocket != null){
                datagramSocket.close();
            }
            if(oos != null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
